/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 *
 * \file
 * \brief Implementation of Directory reader class
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 */
#include "directory.hpp"
#include "owndebug.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <regex.h>
#include <libgen.h>


//*****************************************************************************

CDirectory::CDirectory()
  : iDirectoryHandle(NULL),
    iDirectoryPath()
{
}
//*****************************************************************************

CDirectory::~CDirectory()
{
  Close();
}
//*****************************************************************************

bool CDirectory::Open(const std::string &aDirectory)
{
  bool result = false;
  
  dPrint(8,"Attempting to open directory: '%s'", aDirectory.c_str());

  if (iDirectoryHandle == NULL) {
    iDirectoryHandle = opendir(aDirectory.c_str());
    if (iDirectoryHandle) { 
      dPrint(4,"Succesfully opened directory: '%s'", aDirectory.c_str());
      iDirectoryPath = aDirectory + "/";
      result = true;

    } else {
      dPrintLE(2,"Failed to open directory: '%s'", aDirectory.c_str());
      
    }
  } else {
    dPrint(3,"Directory '%s' is currently open, ignoring request to open '%s'",
           iDirectoryPath.c_str(), aDirectory.c_str());

  }

  return result;
}
//*****************************************************************************

bool CDirectory::GetFileList(TStringArray &aArray, const std::string &aRegExp)
{
  TStringArray notused;
  return GetFileList(aArray, notused, aRegExp);
}
//*****************************************************************************

bool CDirectory::GetFileList(TStringArray &aRegularFileArray, 
                             TStringArray &aDirectoryFileArray,
                             const std::string &aRegExp)
{
  bool result = false;
  int r;
  struct stat filestat;
  regex_t re;

  if (iDirectoryHandle) {
    // Clear the array.
    aRegularFileArray.clear();
    aDirectoryFileArray.clear();

    // Compile regexp (if such exists)
    // Attempt to compile the given regular expression (no SUBs supported)
    if (aRegExp.size() > 0) {
      if (regcomp(&re, aRegExp.c_str(), REG_NOSUB) == 0) {
        dPrint(8,"Successfully compiled regexp '%s'", aRegExp.c_str());
 
      } else {
        dPrint(3,"Failed to compile regexp '%s'! Abort.", aRegExp.c_str());
        return false;

      }
    }

    // Rewind first.
    rewinddir(iDirectoryHandle);

    // Now read.
    struct dirent *dir;
    while( (dir = readdir(iDirectoryHandle)) ) {
      dPrint(15,"Considering entry; '%s'", dir->d_name);
      const std::string fpath = iDirectoryPath + dir->d_name;

      // Apply regexp check (This 'continue's if regexp defined and fails)
      if (aRegExp.size() > 0) {
        r = regexec(&re, dir->d_name, 0, NULL, 0);
        if (r == REG_NOMATCH) {
          // No match to name. Skip!.
          dPrint(15,"File '%s' failed regexp matching.", dir->d_name);
          continue;
        } else {
          dPrint(8,"File '%s' passed regexp matching.", dir->d_name);
        }
      }

      // Stat the file.
      r = stat(fpath.c_str(), &filestat);
      if (r == 0) {
        // Reading stat() OK.
        if (S_ISREG(filestat.st_mode)) {
          // Is regular file.
          if (access(fpath.c_str(), R_OK) == 0) {
            // can read!
            aRegularFileArray.push_back(fpath);
            dPrint(8,"Inserted directory entry (regular file): '%s'", fpath.c_str());

          } else {
            dPrintLE(2,"Failed to get access(R_OK) for file '%s'. Skip.",
                     fpath.c_str());
          }

        } else if (S_ISDIR(filestat.st_mode)) {
          // Is Directory file. (want r+x)
          if (access(fpath.c_str(), R_OK | X_OK) == 0) {
            // can read!
            aDirectoryFileArray.push_back(fpath);
            dPrint(8,"Inserted directory entry (directory file): '%s'", fpath.c_str());
            
          } else {
            dPrintLE(2,"Failed to get access(R_OK|X_OK) for directory file '%s'. Skip.",
                     fpath.c_str());
          }

        } else {
          dPrint(15,"File '%s' is not a regular file or directory. Skip.",
                 fpath.c_str());
          
        }
      } else {
        // stat failed
        dPrintLE(2,"Failed to stat() file '%s'", fpath.c_str());

      }
    }

    // If got regexp, free it.
    if (aRegExp.size() > 0) {
      regfree(&re);
    }

    // Set result
    result = true;
  }
  return result;
}
//*****************************************************************************

bool CDirectory::Close(void)
{
  bool result = false;

  if (iDirectoryHandle) {
    dPrint(8, "Closing directory: '%s'", iDirectoryPath.c_str());

    // Unconditional closedir.
    closedir(iDirectoryHandle);
    iDirectoryHandle = NULL;
    iDirectoryPath.clear();
    result = true;

  } else {
    dPrint(8, "Directory not open so not Closing.");

  }
  return result;
}
//*****************************************************************************

bool CDirectory::IsRegular(const std::string &aFilename)
{
  bool result = false;
  struct stat filestat;
  int r = stat(aFilename.c_str(), &filestat);
  if (r == 0) {
    // Reading stat() OK.
    if (S_ISREG(filestat.st_mode)) {
      result = true;
    }

  } else {
    dPrint(2,"Failed to test whether file '%s' is regular or not!", 
           aFilename.c_str());

  }
  return result;
}
//*****************************************************************************

std::string CDirectory::GetBasename(const std::string &aPath)
{
  std::string result;
  char *bn = new char [ aPath.size() + 1 ];
  strcpy(bn, aPath.c_str());
  result = basename(bn);
  delete[] bn;
  return result;
}
//*****************************************************************************

std::string CDirectory::GetDirname(const std::string &aPath)
{
  std::string result;
  char *bn = new char [ aPath.size() + 1 ];
  strcpy(bn, aPath.c_str());
  result = dirname(bn);
  delete[] bn;
  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
